package com.example.config;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

    public class JDBCTest {
        public static void main(String[] args) {
            Connection conn=null;
            /**这里使用的PreparedStatment,没有使用Statment,是因为有sql注入的风险,
             通过恶意拼接sql语句或者传入非法参数进行恶意篡改sql语句,
             PreparedStatment是采用预编译机制,先将sql预先编译,然后向?处注入值*/
            PreparedStatement ps=null;
            ResultSet rs=null;
            try {
                //1.注册驱动
                Class.forName("com.mysql.cj.jdbc.Driver");
                //2.获得链接
                conn= DriverManager.getConnection("jdbc:mysql://localhost:8023/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false","root","root");
                //3.获取操作数据库对象
                /**?为占位符*/
                String sql="select * from test";
                ps = conn.prepareStatement(sql);
                //4.执行sql语句
                rs=ps.executeQuery();
                //5.处理结果集
                if(rs.next()){
                    System.out.println(rs.getInt("id")+","+rs.getString("name")+","+rs.getString("name"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                //6.释放资源
                if(rs!=null){
                    try{
                        rs.close();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }

                if(ps!=null){
                    try{
                        ps.close();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }

                if(conn!=null){
                    try{
                        conn.close();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }

            }
        }

}
